package com.gzmu.myprint.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.gzmu.myprint.mapper.AismartMapper;
import com.gzmu.myprint.mapper.CostMapper;
import com.gzmu.myprint.mapper.PrintFileMapper;
import com.gzmu.myprint.mapper.PrinterMapper;
import com.gzmu.myprint.model.Aismart;
import com.gzmu.myprint.model.Cost;
import com.gzmu.myprint.model.PrintFile;
import com.gzmu.myprint.model.Printer;
import com.gzmu.myprint.vo.CommonUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static com.gzmu.myprint.constant.Constant.PAGE_NUM;


@Controller
public class PrintController {
    /**
     * 正方形二维码宽度
     */
    private static final int CODE_WIDTH = 480;
    /**
     * 黑点颜色
     */
    private static final int BLACK = 0xFF000000;
    /**
     * 白色
     */
    private static final int WHITE = 0xFFFFFFFF;

    @Autowired
    private PrintFileMapper printFileMapper;

    @Autowired
    private PrinterMapper printerMapper;


    @Autowired
    public CostMapper costMapper;

//    @ResponseBody
//    @RequestMapping(value = "/SelectAismart", produces = "text/html;charset=UTF-8")
//    public String SelectAismart(HttpServletRequest request) {
//
//        Map<String, Object> map = new HashMap<String, Object>();
//        Aismart aismart = aismartMapper.SelectAismart();
//        if (aismart!=null){
//            map.put("status",true);
//            map.put("aismart",aismart);
//        }else{
//            map.put("status",false);
//        }
//        return JSONObject.toJSON(map).toString();
//    }
    @RequestMapping("/jieyin")
    public String jieyin(){
        return "app/jieyin";
    }

    @RequestMapping("/upfile")
    public String upfile(HttpServletRequest request, Model model) {
        String uid = request.getParameter("uid");

        System.out.println("++++upfile uid:" + uid );
        if (uid != null)
            model.addAttribute("uid", uid);
        return "/app/upfile";
    }

    @RequestMapping("/printer")
    public String printer(HttpServletRequest request, Model model) {
        String uid = request.getParameter("uid");
        String pid = request.getParameter("pid");
        String path = request.getParameter("path");
        String name = request.getParameter("name");

        System.out.println("++++printer uid:" + uid + " pid:" + pid + " path" + path  + " name" + name);
        if (uid != null)
            model.addAttribute("uid", uid);
        if (pid != null)
            model.addAttribute("pid", pid);
        if (path != null)
            model.addAttribute("path", path);
        if (name != null)
            model.addAttribute("name", name);
        return "/app/printer";
    }

    @ResponseBody
    @RequestMapping(value = "/inserPrinter", produces = "text/html;charset=UTF-8")
    public String inserPrinter(HttpServletRequest request) {
        String hardid = request.getParameter("hardid");
        String name = request.getParameter("name");
        String gps = request.getParameter("gps");
        String other = request.getParameter("other");
        String [] gpss = gps.split(",");
        System.out.println("++++printer hardid:" + hardid + " name:" + name + " gps" + gps  + " other:" + other );
        Printer printer = new Printer();
        printer.setHardid(hardid);
        printer.setName(name);
        printer.setLatitude(Double.valueOf(gpss[0]));
        printer.setLongitude(Double.valueOf(gpss[1]));
        printer.setOther(other);
        Map<String, Object> map = new HashMap<String, Object>();
        int reValue = printerMapper.insertOrUpdatePrinter(printer);
        if (reValue==1){
            System.out.println("inserPrinter success");
            map.put("result",true);
        }else{
            System.out.println("inserPrinter fail");
            map.put("result",false);
        }
        return JSONObject.toJSON(map).toString();
    }

    @ResponseBody
    @RequestMapping(value = "/selectPrinter", produces = "text/html;charset=UTF-8")
    public String selectPrinter() {
        Map<String, Object> map = new HashMap<String, Object>();

        List<Printer> list = printerMapper.getAllPrinter();
        map.put("list",list);
        return JSONObject.toJSON(map).toString();
    }

    @ResponseBody
    @RequestMapping(value = "/selectCost", produces = "text/html;charset=UTF-8")
    public String selectCost(@RequestParam("uid") String uid) {
        Map<String, Object> map = new HashMap<>();
        List<Cost> list = costMapper.selectCost(uid);
        map.put("list",list);
        return JSONObject.toJSON(map).toString();
    }

    @ResponseBody
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }
        String uid = request.getParameter("uid");
        String fileName = request.getParameter("fileName");
        System.out.println("++++upload uid:" + uid);
        if (fileName==null)
            fileName = file.getOriginalFilename();

        String newName = UUID.randomUUID().toString();
        // 获取系统文件分隔符
        String type = fileName.substring(fileName.lastIndexOf(".") + 1);
        String name = fileName.substring(0,fileName.lastIndexOf("."));
        String nowDate = new SimpleDateFormat("YYYY-MM-dd").format(new Date());
        String timeStr = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date());
        try {
            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            //System.out.println("根目录:" + path.getAbsolutePath());
            File uploadPath = new File(path.getAbsolutePath(),"static/upfile/" + nowDate + "/") ;
            //文件夹路径不存在
            if (!uploadPath.exists() && !uploadPath.isDirectory()) {
                System.out.println("创建路径:" + uploadPath);
                uploadPath.mkdirs();
            }

            String nPath = uploadPath +"/"+ newName + "." + type;
            File newFile = new File(nPath);
            file.transferTo(newFile);
            long pages = CommonUtil.getFilePages(nPath,type);
            System.out.println("pages:" + pages);

            String fileUrl = "/upfile/" + nowDate + "/" + newName + "." + type;
            PrintFile printFile = new PrintFile();
            printFile.setUid(uid);
            printFile.setType(type);
            printFile.setOldName(name);
            printFile.setUrlName(fileUrl);
            printFile.setIsEnble(1L);
            printFile.setTime(timeStr);
            printFile.setPages(pages);

            Map<String, Object> map = new HashMap<String, Object>();
            int reValue = printFileMapper.insertPrintFile(printFile);

            if (reValue==1){
                System.out.println(fileName + " upload success");
                map.put("result",true);
            }else{
                System.out.println(fileName + " upload fail");
                map.put("result",false);
            }
            map.put("name",fileName);
            map.put("path",fileUrl);
            return JSONObject.toJSON(map).toString();
        } catch (IOException e) {
            System.out.println(e.toString());
        }
        return "upload fail";
    }

    @ResponseBody
    @RequestMapping(value = "/fileOfPages", produces = "text/html;charset=UTF-8")
    public String fileOfPages(@RequestParam("uid") int uid, @RequestParam("page") int page) {
        Map<String, Object> map = new HashMap<String, Object>();
        int pages = page * 20;
        System.out.println("+++pages:" + pages);
        List<PrintFile> list = printFileMapper.getFileOfPages(uid, pages, PAGE_NUM);
        int load = list.size()>PAGE_NUM?1:0;
        map.put("load",load);
        map.put("list",list);
        return JSONObject.toJSON(map).toString();
    }

    public static BufferedImage encodeImg(String contents){
        BufferedImage image = null;
        HashMap<EncodeHintType, Comparable> hints = new HashMap<EncodeHintType, Comparable>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);// 纠错等级L,M,Q,H
        hints.put(EncodeHintType.MARGIN, 1); // 边距
        try{
            BitMatrix matrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, CODE_WIDTH, CODE_WIDTH, hints);
            image = new BufferedImage(CODE_WIDTH, CODE_WIDTH, BufferedImage.TYPE_INT_RGB);
            int width = matrix.getWidth();
            int height = matrix.getHeight();
            for(int x = 0; x < width; x++){
                for(int y =0;y < height; y++){
                    image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
                }
            }
        }catch(Exception e){
            System.out.println("生成二维码失败"+e.getMessage());
        }
        return image;
    }

    @RequestMapping("qrcode")
    public void getQRcodeImg(@RequestParam MultipartFile logoFile, HttpServletRequest request, HttpServletResponse resp)
            throws IOException {
        resp.setHeader("Cache-Control", "no-store");
        resp.setHeader("Pragma", "no-cache");
        resp.setDateHeader("Expires", 0);
        resp.setContentType("image/png");

        String content = request.getParameter("content");
        String contentType = logoFile.getContentType();
        System.out.println(contentType);// 输出image/jpeg
        if (contentType.startsWith("image") && content != "") {
            BufferedImage logoImg = ImageIO.read(logoFile.getInputStream());
            BufferedImage qrcodeImg = encodeImg(content);
            BufferedImage image = encodeImgLogo(qrcodeImg, logoImg);
            ImageIO.write(image, "png", resp.getOutputStream());
            //MatrixToImageWriter.writeToStream(bitMatrix, "png", resp.getOutputStream());
        }
    }

    public static BufferedImage encodeImgLogo(BufferedImage twodimensioncode,BufferedImage logo){
        try{
            Graphics2D g = twodimensioncode.createGraphics();
            System.out.println("twodimensioncode:"+twodimensioncode.getWidth());
            int logoWidth = logo.getWidth(null) > twodimensioncode.getWidth()*2 /10 ? (twodimensioncode.getWidth()*2 /10) : logo.getWidth(null);
            int logoHeight = logo.getHeight(null) > twodimensioncode.getHeight()*2 /10 ? (twodimensioncode.getHeight()*2 /10) : logo.getHeight(null);
            System.out.println("logoWidth:"+logoWidth);
            int x = (twodimensioncode.getWidth() - logoWidth) / 2;
            int y = (twodimensioncode.getHeight() - logoHeight) / 2;

            g.drawImage(logo, x, y, logoWidth, logoHeight, null);
            g.drawRoundRect(x, y, logoWidth, logoHeight, 15 ,15);

            g.setStroke(new BasicStroke(2));
            g.setColor(Color.WHITE);
            g.drawRect(x, y, logoWidth, logoHeight);
            g.dispose();
            logo.flush();
            twodimensioncode.flush();
        }catch(Exception e){
            System.out.println("二维码绘制logo失败");
        }
        return twodimensioncode;
    }
}
